package com.heiye.user.biz.consumer;

import com.heiye.framework.common.util.JsonUtils;
import com.heiye.user.biz.constant.MQConstants;
import com.heiye.user.biz.domain.dataobject.UserDO;
import com.heiye.user.biz.domain.mapper.UserDOMapper;
import com.heiye.user.biz.model.dto.mq.UserAvatarMqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: heiye
 * @date: 2025/03/09 下午1:56
 * @version: v1.0.0
 * @description: 用户头像更新消费者
 */
@Slf4j
@Component
@RocketMQMessageListener(
        // Group 组
        consumerGroup = "interact_group_" + MQConstants.TOPIC_USER_AVATAR_UPLOAD,
        // 消费的 Topic 主题
        topic = MQConstants.TOPIC_USER_AVATAR_UPLOAD
)
public class UserAvatarConsumer implements RocketMQListener<Message> {

    @Resource
    private UserDOMapper userDOMapper;

    @Override
    public void onMessage(Message message) {
        // 消息体
        String bodyJsonStr = new String(message.getBody());

        log.info("==> UserAvatarConsumer 消费了消息 {}", bodyJsonStr);

        // 将消息体 Json 字符串转为 DTO 对象
        UserAvatarMqDTO userAvatarMqDTO = JsonUtils.parseObject(bodyJsonStr, UserAvatarMqDTO.class);

        // 判空
        if (Objects.isNull(userAvatarMqDTO)) {
            return;
        }

        // 构建用户信息
        UserDO userDO = UserDO.builder()
                .id(userAvatarMqDTO.getUserId())
                .photoUrl(userAvatarMqDTO.getAvatarUrl())
                .updateTime(userAvatarMqDTO.getUpdateTime())
                .build();

        userDOMapper.updateByPrimaryKeySelective(userDO);
    }
}
